/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Example client using the MottiMapObjectDB SQL extension.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: SQLExtMottiMapObjectDBExample.cpp,v 1.3 2009-11-26 09:42:28 amaula Exp $
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string>
#include <map>
#include <math.h>
#include "owndebug.h"
#include "ownutils.h"
#include "binbag.h"
#include "SQLClient.hpp"
#include "ext/MottiMapObjectDB.hpp"
#include <sys/ioctl.h>


//*****************************************************************************
// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************
// Choose your namespace
using namespace MaCI;
using namespace MaCI::SQL;
using namespace MaCI::SQL::Ext;
//*****************************************************************************
// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************
static std::string datasource;
static std::string datasourceMaCISL;
//*****************************************************************************
static std::map<unsigned int, std::string> sentQueryMap;
//*****************************************************************************
static std::string targetTable = "mapObjects";
static SMottiMapObjectRow posrow;
static bool print_stuff = true;
static std::string where_clause = "abs(x) < 1.0 and abs(y) < 1.0 order by type_id,x";
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tSQLClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tSpecify the data source\n");
  fprintf(stderr,"  \t\t\t\tOR\n");
  fprintf(stderr,"  [-S name]\t\t\tSpecify the data source by MaCISL\n");
  fprintf(stderr,"  [-r]\t\t\t\tToggle Print stuff (Prints a lot)\n\n");
  fprintf(stderr,"  [-W clause]\t\t\t\tWhere clause to give. Inserted as 'WHERE <clause>'"); 
  fprintf(stderr,"\n");

  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int ExecuteExampleClient(gimi::GIMI &g)
{
  // SQL client instance
  // Traditional form, where the GIMI is given as preconnected pointer
  // to the SQLClient instance.
  CSQLClient dc(&g, 0);

  // SQL data instance
  CSQLData dd;
  dd.CreateInternalBinBag();

  // Variable for storing thread id.
  //  ownThreadHandle dummyWatchThread;

  // Init random generator.
  srandom(time(NULL));

  // Assign default target.
  if (datasource.size()) {
    dc.SetDefaultTarget(datasource);

  } else {
    // GIMI is Open(), so we can execute this.
    MaCICtrl::SMaCISL sl(datasourceMaCISL);
    if (sl.IsValidFQMaCISL()) {
      dc.SetDefaultTarget(sl, 3000);
    }
    
  }

  ownRandom_init_time();
  
  // Open.
  bool result;
  if (dc.Open() == KMaCIOK) {
    dPrint(ODINFO,"Succesfully Open():ed SQLClient, BTW, you have connected to service: '%s'",
           dc.GetDefaultTargetMaCISL().ToMaCISLString().c_str());

    // OK, Now construct the 'Helper', using 'poses' as default table.
    //    CMottiMapObjectDB sdb(&dc, "poses");
    CMottiMapObjectDB sdb(&dc, targetTable);

    // Drop table
    printf("Executing sdb.DropTable()...");
    result = sdb.DropTable();
    if (result == false) dPrint(ODTEST,"DROP TABLE failed - assuming table didn't exist for now");
    printf("OK.\n");

    // Create table
    printf("Executing sdb.CreateTable()...");
    result = sdb.CreateTable();
    assert(result == true);
    printf("OK.\n");

    const double ob = ownTime_get_s();
    const int count = 1000;
    printf("Executing %d x sdb.InsertMottiMapObjectDBRow()...", count);
    for(int i=0; i < count; ++i) {
      const float x = ownRandom_get_range(-10.00, 10.00);
      const float y = ownRandom_get_range(-10.00, 10.00);
      
      result = sdb.InsertMottiMapObjectDBRow( SMottiMapObjectRow(1, i, 1, x, y) );
    }
    const double took = ownTime_get_s_since(ob);
    printf("OK (Took %.5lfs, %.2lfms / entry).\n", took, (took / (double)count)*1000.0);


    const double ob2 = ownTime_get_s();
    unsigned int count2 = 0.0;
    TMottiMapObjectResultTable table;
    printf("Executing sdb.GetMottiMapObjects(&t, '%s')...", where_clause.c_str());

    result = sdb.GetMottiMapObjects(table, where_clause);
    if (result) count2 = table.size();
    
    const double took2 = ownTime_get_s_since(ob2);
    printf("OK (Took %.5lfs, %.2lfms / entry).\n", took2, (took2 / (double)count2)*1000.0);


    printf("Printing all elements (%d totals):\n", count2);
    for(EACH_IN_i(table)) {
      printf("Element: %s\n", i->ToString().c_str());
    }

    
    


  } else {
    dPrint(1,"Failed to Open() SQLClient.");

  }

  dPrint(ODSTATUS,"Exit.");
  exit(0); // Do it fast :)
  return 0;
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName;

  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.3 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "W:rn:u:p:s:S:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

    case 'r':
      print_stuff ^= true;
      dPrint(3,"Print_Stuff is now %s.", print_stuff ? "enabled" : "disabled");
      break;

    case 's':
      datasource = optarg;
      dPrint(3,"Using DataSource '%s'", optarg);
      break;

    case 'S':
      datasourceMaCISL = optarg;
      dPrint(3,"Using DataSource MaCISL '%s'", optarg);
      break;

    case 'W':
      where_clause = optarg;
      dPrint(3,"Using WHERE clause: '%s'", optarg);
      break;
      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteExampleClient(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
 * 
 * $Log: not supported by cvs2svn $
 * Revision 1.2  2009-11-26 09:41:03  amaula
 * Added field group_id for separating group access. (another table added but not implemented)
 *
 * Revision 1.1  2009-11-25 10:09:01  amaula
 * Added MottiMapObject database access tools to version control.
 *
 *
 *
 *****************************************************************************/
//*****************************************************************************
//*****************************************************************************


